package edu.mcw.rgd.clinminer.security;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.ldap.core.ContextSource;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator;

public class CustomLdapAuthoritiesPopulator extends
DefaultLdapAuthoritiesPopulator {
	static Logger log = Logger.getLogger(CustomLdapAuthoritiesPopulator.class);
	static Properties props;

	public CustomLdapAuthoritiesPopulator(ContextSource contextSource,
			String groupSearchBase) throws IOException {
		super(contextSource, groupSearchBase);
		props = PropertiesLoaderUtils
				.loadAllProperties("/META-INF/user.properties");
	}

	@Override
	protected Set<GrantedAuthority> getAdditionalRoles(
			DirContextOperations user, String username) {
		Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();

		if (props.containsKey(username)) {
			// extract list of properties
			List<String> externalAuthorities = Arrays.asList(((String) props
					.get(username)).split(","));
			log.debug("Adding " + username + " authorities: "
					+ externalAuthorities);
			// add authorities
			for (String authotity : externalAuthorities) {
				authorities.add(new SimpleGrantedAuthority("ROLE_CLINMINER_"
						+ authotity.trim()));
			}
		}

		return authorities;

	}

}
